package cz.via.wowss.helper;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import cz.via.wowss.controller.MainController;

public class CompanyTypeValueChanger {
	private CompanyType ct;
	private double value;

	public CompanyTypeValueChanger(CompanyType ct, double value) {
		super();
		this.ct = ct;
		this.value = value;
	}

	private void doChange(CompanyType ct, double value) {
		callQuery(ct, value);
		List<CompanyTypeConnection> connections = CompanyTypeConnections.getCompanyConnections(ct);
		if (connections == null)
			return;
		for (CompanyTypeConnection ctc : connections) {
			doChange(ctc.getCompany2(), ctc.getConnection() * value);
		}
	}

	public void doChange() {
		doChange(ct, value);
	}

	private void callQuery(CompanyType ct, double value) {
		value = value * 100 + 100;
		int val = (int) value;
		String query = "UPDATE Company c SET c.value = c.value * " + val + "/100 WHERE c.type = :ct";
		EntityManager em = MainController.emf.createEntityManager();
		EntityTransaction t = em.getTransaction();
		t.begin();
		Query q = em.createQuery(query);
		q.setParameter("ct", ct.getId());
		q.executeUpdate();
		t.commit();
	}
}
